//
//  Strore_Root_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/10/30.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "Strore_Root_Controller.h"
//untils
#import "Global.h"
#import "UIColor+Hex.h"
#import "ManagerGlobeUntil.h"
#import "NSString+Conversion.h"
#import "UIImage+ColorToImage.h"
#import "AppDelegate.h"
//view
#import "Strore_CollectionReusableView.h"
#import "Strore_root_goodsGroup_view.h"
#import "Strore_CollectionViewCell.h"
#import "EmptyPageView.h"
#import "Strore_Root_Top_ItemView.h"
#import "StoreNavigationTitleView.h"
//model
#import "Strore_root_goodsGroup_model.h"
//controller
#import "Strore_detailController.h"
#import "ManagerHttpBase.h"
#import "SearchRootController.h"
#import "FMDBManager.h"
//vendor
#import "MJRefresh.h"
#import "MTA.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
@interface Strore_Root_Controller ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate,Strore_root_goodsGroupDelegate,Strore_CollectionViewCellDelegate,EmptyPageViewDelegate,Strore_Root_Top_ItemViewDelegate,StoreNavigationTitleViewDelegate>
{
    Strore_CollectionReusableView *_headerView;
    NSInteger _requestPage;//当前请求页
    NSInteger _totalCount;//数据总条数
    UIView *_maskView;
    Strore_root_goodsGroup_view *_groupView;
    CALayer     *layer;
}
@property(nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic, strong)NSMutableArray *loopImagesData;//存轮播图数据（包括图片地址，id等）
@property(nonatomic, strong)NSMutableArray *images;//图片数组
@property(nonatomic, strong)NSMutableArray *storeListArr;//商品列表
@property (strong,nonatomic)EmptyPageView *emptyView;//空页面
@property (strong,nonatomic)EmptyPageView *emptyNoGoodsView;//空页面
@property (nonatomic,strong)NSString *secondCode;//二级分类的code
@property (nonatomic,strong) UIBezierPath *path;// 动画路径
@property (nonatomic,strong) UIImage *goodImage;//商品图片
@property (nonatomic,strong)UIButton *toTopbtn;//回到顶部按钮
@property (nonatomic,strong)NSString *sortType;//排序类型
@property (nonatomic,strong)NSDictionary *dicData;
@property (nonatomic ,strong) Strore_Root_Top_ItemView  *topItemView;//购物车视图
@property (nonatomic)BOOL ziYingBtnSelected; //自选按钮状态

@end

@implementation Strore_Root_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    [self setnavgationView];
    [self setupSubView];
    _ziYingBtnSelected =NO;
    _requestPage = 1;
    _loopImagesData = [[NSMutableArray alloc]init];
    _images = [[NSMutableArray alloc]init];
    _storeListArr = [[NSMutableArray alloc]init];
    _sortType =@"1";
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self changeCategoryWithTitle];
    _maskView.hidden = YES;
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
       [self loadStoreListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
        [self loadLoopImagesData];
        [self loadGoodsGroup];
    }else{
        if (_storeListArr.count == 0) {
            _emptyView.hidden =NO;
            _collectionView.hidden=YES;
        }
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"便利店"];
    //如果分类请求数据为空（可能是网络慢造成的）
    if (_groupView.goodsGroupArr.count == 0) {
        [self loadGoodsGroup];
    }
    [ManagerGlobeUntil sharedManager].isHomeToStore =NO;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"便利店"];
}
#pragma mark -- request Data   请求轮播图，图片
- (void)loadLoopImagesData {
//    //请求参数说明： SIGNATURE  设备识别码
   //                 STOREID     商品ID
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"ad/storeAdList" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            // NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                [weakSelf.loopImagesData removeAllObjects];
                [_images removeAllObjects];
                [weakSelf.loopImagesData addObjectsFromArray:[dataDic objectForKey:@"OBJECT"]];
                if (weakSelf.loopImagesData.count != 0) {//返回轮播图数据不为空
                    for (NSDictionary *dic in weakSelf.loopImagesData) {
                        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",baseImageUrl,[dic objectForKey:@"THUMB"]];
                        [weakSelf.images addObject:imageUrl];
                        [_headerView resetLoopScrollViewImages:[weakSelf.images copy]];
                    }
                } else {
                    [_headerView resetLoopScrollViewImages:@[@"productDetail_Default_loopImage"]];
                }
            }
        }
    } failure:^(bool isFailure) {
    }];
}
//请求商品列表
- (void)loadStoreListDataWithProductType:(NSString*)productType withPage:(NSInteger)page requestCount:(NSInteger)requestCount{
    //请求参数说明： SIGNATURE  设备识别码
    //      STOREID     商品ID
    //      CATEGORYCODE 类别代码 1：蔬菜水果，2：酒水饮料，3：生活百货，4：粮油调料，5：营养早餐
    //      TYPE 优惠类型 1：普通，2：推荐，3：限量，4：一元购
    //      PAGENUM  页码
    //      PAGESIZE 数量
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..." inView:self.view];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    [parameter setObject:productType forKey:@"CATEGORYONCODE"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    if (self.ziYingBtnSelected) {
        [parameter setObject:@"1" forKey:@"ISSELF"];
    }else{
         [parameter setObject:@"0" forKey:@"ISSELF"];
    }
    [parameter setObject:@"1" forKey:@"TYPE"];
    [parameter setObject:[NSNumber numberWithInteger:page] forKey:@"PAGENUM"];
    [parameter setObject:[NSNumber numberWithInteger:requestCount] forKey:@"PAGESIZE"];
    [parameter setObject:_sortType forKey:@"ORDERBY"];
    if (_secondCode.length !=0) {
        [parameter setObject:_secondCode forKey:@"CATEGORYTWCODE"];
    }
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"goods/list" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                _totalCount = [[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOTALROW"]] integerValue];
                if (_requestPage == 1) {//请求第一页清空数据
                    [weakSelf.storeListArr removeAllObjects];
                }
                [weakSelf.storeListArr addObjectsFromArray:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"LIST"]];
                _emptyView.hidden =YES;
                _collectionView.hidden=NO;
                if (_storeListArr.count == 0) {//如果数据为0隐藏返回顶部按钮
                    weakSelf.toTopbtn.hidden =YES;
                    _emptyNoGoodsView.hidden=NO;
                }else{
                    _emptyNoGoodsView.hidden=YES;
                }
            }else {//请求失败
                if (msg.length == 0) {
                    msg = @"请求数据出现异常";
                }
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
                [weakSelf.storeListArr removeAllObjects];
                weakSelf.toTopbtn.hidden =YES;
            }
            [weakSelf.collectionView reloadData];
        }
        [weakSelf endRefresh];
        [self loadGoodsGroup];
        
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        [weakSelf endRefresh];
        [weakSelf.storeListArr removeAllObjects];
        [weakSelf.collectionView reloadData];
         weakSelf.toTopbtn.hidden =YES;
    }];
}
//请求商品分组数据
- (void)loadGoodsGroup {
    //    //请求参数说明： SIGNATURE  设备识别码
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:mode.storeID forKey:@"STOREID"];
    if (self.ziYingBtnSelected) {
        [parameter setObject:@"1" forKey:@"ISSELF"];
    }else{
        [parameter setObject:@"0" forKey:@"ISSELF"];
    }
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"common/category" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            // NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                [_groupView.goodsGroupArr removeAllObjects];
                [_groupView.goodsGroupArr addObjectsFromArray:[dataDic objectForKey:@"OBJECT"]];
                [_groupView.tableViewOfGroup reloadData];
                [weakSelf leftTableViewSeleteStatrAndRightTableDataWithArray:_groupView.goodsGroupArr ];
            }else {//请求失败
            }
        }
        
    } failure:^(bool isFailure) {
    }];
}
-(void)leftTableViewSeleteStatrAndRightTableDataWithArray:(NSArray *)dataArray
{
    NSIndexPath *indexPath =[NSIndexPath indexPathForRow:0 inSection:0];
    NSInteger selectedIndex =0;
    if ([[[ManagerGlobeUntil sharedManager] bigClassTitle] isEqualToString:@"生鲜蔬果"]) {
        
    } else if ([[[ManagerGlobeUntil sharedManager] bigClassTitle] isEqualToString:@"生活百货"]) {
        selectedIndex =3;
    } else if ([[[ManagerGlobeUntil sharedManager] bigClassTitle] isEqualToString:@"粮油调料"]) {
       selectedIndex =2;
    } else if ([[[ManagerGlobeUntil sharedManager] bigClassTitle] isEqualToString:@"酒水饮料"]) {
        
        selectedIndex =1;
    }
    indexPath =[NSIndexPath indexPathForRow:selectedIndex inSection:0];
    [_groupView.tableViewOfGroup selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    if (dataArray.count !=0) {
        [_groupView.rightGroupArray removeAllObjects];
        NSDictionary *dic = [dataArray objectAtIndex:selectedIndex];
        _groupView.firstCode =[NSString stringTransformObject:[dic objectForKey:@"CODE"]];
        for (NSInteger i=0; i<[[dic objectForKey:@"CHILDREN"] count]+1; i++) {
            Strore_root_goodsGroup_model *model =[[Strore_root_goodsGroup_model alloc]init];
            if (i == 0) {
                model.groupsName =@"全部";
                model.groupsCount =[NSString stringTransformObject:[dic objectForKey:@"GOODSCOUNT"]];
                model.groupsCode =@"";
            }else{
                NSDictionary *dicdata =[[dic objectForKey:@"CHILDREN"] objectAtIndex:i-1];
                model.groupsName =[NSString stringTransformObject:[dicdata objectForKey:@"NAME"]];
                model.groupsCount =[NSString stringTransformObject:[dicdata objectForKey:@"GOODSCOUNT"]];
                model.groupsCode =[NSString stringTransformObject:[dicdata objectForKey:@"CODE"]];
                model.isChecked =NO;
            }
            [_groupView.rightGroupArray addObject:model];
        }
        _groupView.rightSelectedIndex =0;
            [_groupView.tableViewOfDetail reloadData];
    }
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.storeListArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Strore_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Strore_CollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
       NSDictionary *dataDic = [self.storeListArr objectAtIndex:indexPath.row];
    cell.delegate =self;
    cell.indexPath =indexPath;
    [cell.layer setMasksToBounds:YES];
    [cell.layer setCornerRadius:5.0];
    [cell retSubViewWithData:dataDic];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    _headerView = [collectionView  dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Strore_CollectionReusableView" forIndexPath:indexPath];
    _headerView.delegate = (id <Strore_CollectionReusableViewDelegate>)self;
    return _headerView;
    
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    Cell.alpha = 0.6;
}
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    Cell.alpha = 1;
}
#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDic = [self.storeListArr objectAtIndex:indexPath.row];
    Strore_detailController *detailVc=[[Strore_detailController alloc]init];
    detailVc.goodsID =  [NSString stringTransformObject:[dataDic objectForKey:@"ID"]] ;
    detailVc.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVc animated:YES];
}
#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(VIEW_WIDTH, 110);
}
#pragma mark -- Strore_CollectionReusableViewDelegate 点击轮播图跳转
- (void)selectedLoopImageIndex:(NSInteger)index  {
    NSDictionary *dataDic = [self.loopImagesData objectAtIndex:index];
    Strore_detailController *detailVc=[[Strore_detailController alloc]init];
    detailVc.goodsID =  [NSString stringTransformObject:[dataDic objectForKey:@"GOODSID"]] ;
    detailVc.isSelf = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    [self.navigationController pushViewController:detailVc animated:YES];
}
#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.view.bounds.size.height) {
        self.toTopbtn.hidden = NO;
    } else {
        self.toTopbtn.hidden = YES;
    }
}
#pragma mark --Strore_Root_Top_ItemViewDelegate
-(void)kStroreGoodSGroupClickWithSelectedState:(BOOL)selectedState
{
    if (selectedState) {
         _maskView.hidden = NO;
    }else{
         _maskView.hidden =YES;
    }
}
-(void)kStroreSalesVolumeClick
{
     _sortType =@"2";
     _maskView.hidden =YES;
    //按排序请求数据
    [self loadGoodsListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
}
-(void)kStroreProprietaryBtnWithSelectedState:(BOOL)selectedState
{
    _ziYingBtnSelected =selectedState;
    _maskView.hidden =YES;
   [self loadGoodsListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
}
-(void)kStrorePriceBtnClickWithSort:(NSString *)sort
{
    if ([sort isEqualToString:@"1"]) {
        _sortType = @"3";
    }else if([sort isEqualToString:@"2"]){
        _sortType = @"4";
    }
    _maskView.hidden =YES;
    //按排序请求数据
    [self loadGoodsListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
}
#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
   if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
       _requestPage = 1;
       [self loadStoreListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle ] withPage:_requestPage requestCount:kRequestLimit];
   } else {
       [self endRefresh];
   }
}
-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (_requestPage*kRequestLimit < _totalCount) {
            _requestPage++;
            [self loadStoreListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle ] withPage:_requestPage requestCount:kRequestLimit];
        } else {
            [_collectionView setFooterRefreshingText:@"已加载完全部商品~"];
            [self endRefresh];
        }
    } else {
        [self endRefresh];
    }
}
- (void)endRefresh
{
    [self.collectionView headerEndRefreshing];
    [self.collectionView footerEndRefreshing];
}
-(void)OnTapMaskView:(UITapGestureRecognizer *)sender{
    UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
    UIButton *sanjiaoBtn = (UIButton *)[self.topItemView viewWithTag:120];
    [btn setTitleColor:[UIColor colorWithHexString:@"#db3b34"] forState:UIControlStateNormal];
    btn.selected = NO;
    sanjiaoBtn.selected = NO;
    _maskView.hidden = YES;
}
-(void)toTopBtnClick
{
    [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}
//立即重试按钮
-(void)buttonClick
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadStoreListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
        [self loadLoopImagesData];
        [self loadGoodsGroup];
    }else{
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络还没好,请重试~" inView:nil];
    }
}
#pragma mark --Strore_Root_Top_ItemViewDelegate
-(void)beatNavigationTitleViewToSearchView{
    SearchRootController *searchVC = [[SearchRootController alloc]init];
    [self.navigationController pushViewController:searchVC animated:NO];
}
#pragma mark - Strore_root_goodsGroup_viewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath withFirstCode:(NSString *)firstCode withSecondCode:(NSString *)SecondCode Name:(NSString *)name
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [ManagerGlobeUntil sharedManager].bigClassTitle =[NSString itemTitleWithProductType:firstCode];
        _secondCode =SecondCode;
        _sortType =@"1";
        [self loadStoreListDataWithProductType:[NSString productTypeWithItemTitle:[ManagerGlobeUntil sharedManager].bigClassTitle] withPage:1 requestCount:kRequestLimit];
    }
     [self.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
    UIButton *sjBtn = (UIButton *)[self.topItemView viewWithTag:120];
    sjBtn.selected = NO;
    UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
    if([name isEqualToString:@"全部"])
    {
        name =[ManagerGlobeUntil sharedManager].bigClassTitle;
    }
    [btn setTitle:name forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"#db3b34"] forState:UIControlStateNormal];
    btn.selected=NO;
    _maskView.hidden = YES;
}
#pragma mark -- Strore_CollectionViewCellDelegate
-(void)selectedItemAtIndexPath:(NSIndexPath *)indexPath buttonPoint:(CGPoint)buttonPonint
{
    _dicData =[_storeListArr objectAtIndex:indexPath.row];
     _goodImage =[UIImage createImageWithImageUrlString:[NSString stringTransformObject:[_dicData objectForKey:@"THUMB"]]];
    if (_goodImage == nil) {
        _goodImage=[UIImage imageNamed:@"productDetail_Default"];
    }
    UICollectionViewCell *Cell = [self.collectionView cellForItemAtIndexPath:indexPath];
     CGPoint cellInSelfViewPoint = [[Cell superview] convertPoint:CGPointMake(Cell.frame.origin.x, Cell.frame.origin.y) toView:self.view];
        self.path = [UIBezierPath bezierPath];
        [_path moveToPoint:CGPointMake(cellInSelfViewPoint.x +buttonPonint.x+5, cellInSelfViewPoint.y +buttonPonint.y+5)];
        [_path addLineToPoint:CGPointMake(VIEW_WIDTH/10*7,VIEW_HEIGHT-49-64)];
         [self startAnimation];
}
#pragma mark --加入购物车
-(void)inToShopCarWithDic:(NSDictionary *)dicData
{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID=[NSString stringISNull:mode.storeID];
    NSString *goodID=[NSString stringTransformObject:[dicData objectForKey:@"ID"]];
    NSString *name =[NSString stringTransformObject:[dicData objectForKey:@"NAME"]];
    NSData *picture =UIImagePNGRepresentation(_goodImage);
    NSString *type=[NSString stringTransformObject:[dicData objectForKey:@"TYPE"]];
    NSString *price=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"SELLPRICE"]] floatValue]];
    NSString *oldprice=[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dicData objectForKey:@"MARKETPRICE"]] floatValue]];
    NSString *ischoose =@"1";
    NSString *isProprietary =[NSString stringTransformObject:[dicData objectForKey:@"ISSELF"]];
    if ([isProprietary isEqualToString:@"1"]) {
        shopID =@"";
    }
    NSMutableDictionary *goodSqlite=[[FMDBManager sharedManager]QueryDataWithShopID:shopID goodID:goodID];
    if (goodSqlite.count ==0) { //购物车没数据 先存
        NSString *buynum= @"1";
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:buynum ischoose:ischoose isProprietary:isProprietary];
    }else{//购物车有数据 更新数据
        NSString *str=[goodSqlite objectForKey:@"buynum"];
        if ([isProprietary isEqualToString:@"1"])
        {
            [[FMDBManager sharedManager]deleteOneDataWithgoodID:goodID];
        }else{
            [[FMDBManager sharedManager]deleteOneDataWithShopID:shopID goodID:goodID];
        }
        //字符串 变数字 然后加减完 变回字符串
        NSInteger buynum =str.integerValue;
        buynum++;
        NSString *srr=[NSString stringWithFormat:@"%ld",(long)buynum];
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:srr ischoose:ischoose isProprietary:isProprietary];
    }
}
#pragma mark -- 初始化视图
- (void)setupSubView {
    [self setnavgationView];
    [self setCollectionView];
    [self initMaskView];
}
- (void)setnavgationView {
    StoreNavigationTitleView *bottomView = [[StoreNavigationTitleView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 44)];
    bottomView.delegate =self;
    self.navigationItem.titleView =bottomView;
}
//遮罩页
-(void)initMaskView{
    _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, HightScalar(43), [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64-HightScalar(43)-49)];
    _maskView.backgroundColor = [UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:0.5];
    [self.view addSubview:_maskView];
    _maskView.hidden = YES;
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapMaskView:)];
    tap.delegate = self;
    [_maskView addGestureRecognizer:tap];
    //分组
    _groupView = [[Strore_root_goodsGroup_view alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(320))];
    _groupView.delegate = self;
    [_maskView addSubview:_groupView];
}
- (void)setCollectionView {
    //数据为空时显示的View
    _emptyView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49) EmptyPageViewType:kStoreRootView];
    _emptyView.backgroundColor=[UIColor whiteColor];
    _emptyView.hidden=YES;
    _emptyView.delegate =self;
    [self.view addSubview:_emptyView];
    //顶部按钮
    _topItemView =[[Strore_Root_Top_ItemView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(43))];
    _topItemView.delegate = self;
    [self.view addSubview:_topItemView];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 8;
    layout.minimumLineSpacing = 8;
    layout.itemSize = CGSizeMake((self.view.bounds.size.width-24)/2, HightScalar(270));
    layout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8);
    CGRect collectionViewFrame = CGRectMake(0, HightScalar(43), self.view.bounds.size.width, VIEW_HEIGHT - 49 - 64-HightScalar(43));
    _collectionView = [[UICollectionView alloc]initWithFrame:collectionViewFrame collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor colorWithHexString:@"#efeeee"];
    [_collectionView registerClass:[Strore_CollectionViewCell class] forCellWithReuseIdentifier:@"Strore_CollectionViewCell"];
    [_collectionView registerClass:[Strore_CollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Strore_CollectionReusableView"];
    _collectionView.delegate = self;
    //添加下拉刷新
    [_collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //添加上拉加载更多
    [_collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    _emptyNoGoodsView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0,HightScalar(60),VIEW_WIDTH , CGRectGetHeight(_collectionView.bounds)-110) EmptyPageViewType:kStoreNoGoodsView];
    _emptyNoGoodsView.backgroundColor=[UIColor clearColor];
    _emptyNoGoodsView.hidden=YES;
    [self.view addSubview:_emptyNoGoodsView];
    //返回顶部按钮
    _toTopbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    _toTopbtn.hidden =YES;
    _toTopbtn.frame= CGRectMake(VIEW_WIDTH-70, VIEW_HEIGHT-64-49-60, 40, 40);
    [_toTopbtn setImage:[UIImage imageNamed:@"store_btn_back_top"] forState:UIControlStateNormal];
    [_toTopbtn addTarget:self action:@selector(toTopBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_toTopbtn];
    
}
#pragma mark - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isKindOfClass:[UITableView class]]) {
        return NO;
    }
    if ([touch.view.superview isKindOfClass:[UITableView class]]) {
        return NO;
    }
    if ([touch.view.superview.superview isKindOfClass:[UITableView class]]) {
        return NO;
    }
    if ([touch.view.superview.superview.superview isKindOfClass:[UITableView class]]) {
        return NO;
    }
    return YES;
}
#pragma mark--加入物品动画
-(void)startAnimation
{
    if (!layer) {
        layer = [CALayer layer];
        layer.contents = (__bridge id)_goodImage.CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0,30, 30);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];
}
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    narrowAnimation.duration = 0.6f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:0.2f];
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,narrowAnimation];
    groups.duration = 0.8f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //    [anim def];
    if (anim == [layer animationForKey:@"group"]) {
        [layer removeFromSuperlayer];
        layer = nil;
        //购物车按钮动画
        [self inToShopCarWithDic:_dicData];
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.3f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-1.5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:1.5];
        shakeAnimation.autoreverses = YES;
        AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        RDVTabBarItem *tabBarItem = (RDVTabBarItem*)[appDelegate.tabBarController.tabBar.items objectAtIndex:3];
        [tabBarItem.layer addAnimation:shakeAnimation forKey:nil];
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)cancelButtonState
{
    for (int i = 0; i < 3; i++) {
        UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100+i];
        UIButton *sanjiaoBtn = (UIButton *)[self.topItemView viewWithTag:120+i];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.selected = NO;
        sanjiaoBtn.selected = NO;
    }
}
//改变分类名称
-(void)changeCategoryWithTitle
{
    NSString *categoryTitle = @"";
    if ([ManagerGlobeUntil sharedManager].isHomeToStore) {//从首页选中大类进入便利店
        //改变分类名称
        _sortType =@"1";
        categoryTitle = [ManagerGlobeUntil sharedManager].bigClassTitle;
        self.secondCode = @"";
        [self leftTableViewSeleteStatrAndRightTableDataWithArray:_groupView.goodsGroupArr];
        [self cancelButtonState];
        UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
        [btn setTitleColor:[UIColor colorWithHexString:@"#db3b34"] forState:UIControlStateNormal];
        _ziYingBtnSelected =NO;
         [self.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
    } else {//不是从首页进入便利店
        if ([ManagerGlobeUntil sharedManager].bigClassTitle.length == 0) {//切换tabBar进入便利店且大分类为空的情况
            _sortType =@"1";
            categoryTitle = @"生鲜蔬果";
            [ManagerGlobeUntil sharedManager].bigClassTitle =@"生鲜蔬果";
              [self leftTableViewSeleteStatrAndRightTableDataWithArray:_groupView.goodsGroupArr];
            [self cancelButtonState];
            UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
            [btn setTitleColor:[UIColor colorWithHexString:@"#db3b34"] forState:UIControlStateNormal];
        } else {//从其他页面进入便利店，大分类或二级分类不为空
            UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
            categoryTitle = btn.titleLabel.text;
            UIButton *sanjiaoBtn = (UIButton *)[self.topItemView viewWithTag:120];
            btn.selected = NO;
            sanjiaoBtn.selected = NO;

        }
        
    }
    UIButton *btn = (UIButton *)[self.topItemView viewWithTag:100];
    [btn setTitle:categoryTitle forState:UIControlStateNormal];
}
-(void)loadGoodsListDataWithProductType:(NSString *)type withPage:(NSInteger)page requestCount:(NSInteger)requestCount{

        if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
            [self loadStoreListDataWithProductType:type withPage:page requestCount:requestCount];
        }else{
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络异常，请重试~" inView:self.view];
         }
}


@end
